<?php
/**
 * Controller
 * 
 * 控制器基类
 *
 * @author   songhuan <iphper@yeah.net>
 * @version   $Id: Controller.php 1 2010-08-10 14:40:00Z $
 */
abstract class Controller
{
	/**
     * @var Dispatcher
     */
    protected $_dispatcher = null;
    
    /**
	 * @var Object 模板引擎
	 */
    public $view = null;
    
    /**
     * @param Dispatcher $dispatcher
     */
	public function __construct(Dispatcher $dispatcher)
    {
		$this->_dispatcher = $dispatcher;
		
		require_once V::$config['view']['object'];
		$this->view = View::getInstance();
		
        if (method_exists($this, 'init')) 
        	$this->init();
    }

	/**
     * 转向另一个 controller/action.
     *
     * @param string $action
     * @param string $controller
     * @return void
     */
    final protected function forward($action, $controller = null)
    {
		$this->_dispatcher->_action = $action;
        if ($controller) 
            $this->_dispatcher->_controller = $controller;

		$this->_dispatcher->run();
    }

    /**
     * 跳转到另一个URL地址
     *
     * @param string $url
     * @param array $options Options to be used when redirecting
     * @return void
     */
    protected function redirect($msg = '', $url, $time = 1)
    {
        $time = (int) $time;
		if (headers_sent()) 
		{
			$html = "<meta http-equiv='refresh' content='{$time}; url={$url}'>";
			if ($time > 0)
				$html .= $msg;
			
			echo $html;
		}
		else 
		{
			if ($time > 0) 
			{
				header("refresh:{$time}; url={$url}");
				echo $msg;
			}
			else 
				header('location: '.$url);
		}
		exit;
    }
    
    /**
     * 设置模板引擎
     * 
     * @param ViewObject $view
     * @return void
     */
    public function preDispatch()
    {	

    }
	
    /**
     * 解析模板
     * 
     * @param ViewObject $view
     * @return void
     */
    public function postDispatch()
    {
    	$this->display();
    }
    
    /**
     * 解析并显示模板
     * 
     * @param $tplname 模板名称
     * @return void
     */
	public function display($tplname = null)
	{
		if (null === $tplname) 
			$tplname = $this->_dispatcher->_controller . DS . $this->_dispatcher->_action;
		
		$this->view->display($tplname . V::$config['view']['tpl_suffix']);	
	}
}
